from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse
from .models import Post, Category, Tag
from comments.models import Comment
import markdown


# Create your views here.

def index(request):
    context = {
        "post_list": Post.objects.all().order_by("-created_time"),
        "category_list": Category.objects.all(),
        "tag_list": Tag.objects.all()
    }
    return render(request, 'index.html', context=context)


def detail(request, pk):
    context = {
        "post": get_object_or_404(Post, pk=pk),
        "category_list": Category.objects.all(),
        "tag_list": Tag.objects.all(),
        "comment_list": Comment.objects.all().filter(post_id=pk).order_by('-created_time')
    }
    return render(request, 'detail.html', context=context)


def edit(request):
    if request.method == "GET":
        context = {
            "category_list": Category.objects.all(),
            "tag_list": Tag.objects.all()
        }
        return render(request, 'edittest.html', context=context)
    elif request.method == "POST":
        title = request.POST.get("title")
        body = request.POST.get("body")
        category = request.POST.get("category").split("-")[1]
        excerpt = request.POST.get("excerpt")
        tags = request.POST.get("tags").split("-")[1]
        post = Post(title=title, body=body, category=category, tags=tags, excerpt=excerpt, author=1)
        post.save()
        return redirect(post)
